<?php

class RegularTransaction extends AppModel {

    var $name = 'RegularTransaction';
    var $displayField = 'name';
    var $validate = array(
        'user_id' => array(
            'numeric' => array(
                'rule' => array('numeric'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'account_id' => array(
            'numeric' => array(
                'rule' => array('numeric'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'interval' => array(
            'notempty' => array(
                'rule' => array('notempty'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'delay' => array(
            'numeric' => array(
                'rule' => array('numeric'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'name' => array(
            'notempty' => array(
                'rule' => array('notempty'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'amount' => array(
            'numeric' => array(
                'rule' => array('numeric'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
    );
    //The Associations below have been created with all possible keys, those that are not needed can be removed

    var $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Account' => array(
            'className' => 'Account',
            'foreignKey' => 'account_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );
    var $hasMany = array(
        'Transaction' => array(
            'className' => 'Transaction',
            'foreignKey' => 'regular_transaction_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );

    function getRecentRegTransactions($user_id, $account_id) {
        // Get list of regular transactions for this user
        $regularTransactionIds = $this->find('list', array(
            'conditions' => array(
                'RegularTransaction.user_id' => $user_id,
                'RegularTransaction.account_id' => $account_id,
                )));
        // Get most recent entry in 'transactions' for each RegularTransaction
        unset($mostRecentRegularTransactions);
        foreach ($regularTransactionIds as $regularTransactionId => $regularTransactionName) {
            $mostRecentRegularTransactions[] = $this->Transaction->find('first', array(
                'conditions' => array('Transaction.regular_transaction_id' => $regularTransactionId),
                'fields' => array('Transaction.post_date', 'RegularTransaction.*'),
                'order' => array('Transaction.post_date DESC')
                    ));
        }

        return($mostRecentRegularTransactions);
    }

    function forecast($account_id = null, $targetDate = 'today', $user_id = 1) {

        $targetDate = (strtolower($targetDate) == 'today') ? new DateTime() : new DateTime($targetDate);
        // debug($targetDate);
        // 
         
        // Get list of regular transactions for this user

        $mostRecentRegularTransactions = $this->getRecentRegTransactions($user_id, $account_id);

        foreach ($mostRecentRegularTransactions as $t) {
            if (!isset($t['RegularTransaction']))
                break;
            
            //debug($t);
            
            $transInterval = $t['RegularTransaction']['interval'];
            $transDelay = $t['RegularTransaction']['delay'];

            $lastTransaction = new DateTime($t['Transaction']['post_date']);
            $tSpan = $lastTransaction->diff($targetDate);

            $spanInterval = ($t['RegularTransaction']['interval'] == 'd') ? 'days' : $t['RegularTransaction']['interval'];

            // if the interval specified in the record is over the delay..
            while ($tSpan->$spanInterval >= $transDelay) {

                $dateInterval = 'P' . $transDelay . strtoupper($transInterval);
                $nextTransaction = $lastTransaction->add(new DateInterval($dateInterval));

                //Create transaction

                $this->Transaction->create();

                $nextPostDate = $nextTransaction->format('Y-m-d');
                $next['Transaction'] = array(
                    'id' => null,
                    'user_id' => $user_id,
                    'account_id' => $account_id,
                    'name' => '!R! - ' . $t['RegularTransaction']['name'],
                    'amount' => $t['RegularTransaction']['amount'],
                    'regular_transaction_id' => $t['RegularTransaction']['id'],
                    'post_date' => $nextPostDate,
                    'verified' => 0
                );

                $this->Transaction->save($next);

                $lastTransaction = $nextTransaction;
                $tSpan = $lastTransaction->diff($targetDate);
            }
        }
    }
}
